using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;
using Wxy.Res.Config;

namespace Wxy.Res.Net
{
    public class ResNetUtils
    {
        public static async UniTask<byte[]> DownloadResAsync(string serverResPath)
        {
            if (string.IsNullOrEmpty(serverResPath))
            {
                Debug.LogError("服务器路径为空或无效");
                return null;
            }

            // 确保在主线程中调用 UnityWebRequest
            await UniTask.SwitchToMainThread();

            UnityWebRequest unityWebRequest = UnityWebRequest.Get(serverResPath);
            unityWebRequest.timeout = 10;

            try
            {
                await unityWebRequest.SendWebRequest();

                if (unityWebRequest.result != UnityWebRequest.Result.Success)
                {
                    Debug.LogError("服务器错误: " + unityWebRequest.error);
                    return null;
                }

                // 下载成功，处理AssetBundle
                byte[] assetBundleData = unityWebRequest.downloadHandler.data;
                return assetBundleData;
            }
            catch (Exception ex)
            {
                Debug.LogError("下载过程中发生异常: " + ex.Message);
            }

            return null;
        }
    }
}